package com.lx.Utils;

/**
 * @author lixing
 * @date 2021/6/5 15:02
 */

import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

public class XMLMessage {

    protected String toUserName;
    protected String fromUserName;
    protected String msgType;
    protected String content;

    /**
     * 回复消息
     * @param toUserName 接收方帐号（收到的OpenID）
     * @param fromUserName 开发者微信号
     * @param content
     */
    public XMLMessage(String toUserName, String fromUserName, String content) {
        this.toUserName = toUserName;
        this.fromUserName = fromUserName;
        this.msgType = "text";
        this.content = content;
    }


    public String toXML() {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        sb.append("<ToUserName><![CDATA[" + toUserName + "]]></ToUserName>");
        sb.append("<FromUserName><![CDATA[" + fromUserName + "]]></FromUserName>");
        sb.append("<CreateTime>" + System.currentTimeMillis() / 1000 + "</CreateTime>");
        sb.append("<Content><![CDATA[" + content + "]]></Content>");
        sb.append("<MsgType><![CDATA[" + msgType + "]]></MsgType>");
        sb.append("</xml>");
        return sb.toString();
    }

    public boolean outputStreamWrite(OutputStream outputStream) {
        try {
            outputStream.write(toXML().getBytes("utf-8"));
            outputStream.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean outputStreamWrite(OutputStream outputStream, WXBizMsgCrypt bizMsgCrypt) {
        if (bizMsgCrypt != null) {
            try {
                String outputStr = bizMsgCrypt.encryptMsg(toXML(), System.currentTimeMillis() + "", UUID.randomUUID().toString());
                outputStream.write(outputStr.getBytes("utf-8"));
                outputStream.flush();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            } catch (AesException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        } else {
            return outputStreamWrite(outputStream);
        }
    }

    public String getToUserName() {
        return toUserName;
    }

    public String getFromUserName() {
        return fromUserName;
    }

    public String getMsgType() {
        return msgType;
    }

}